# 查询IP归属地
# 通过IP查询归属地
import random

import requests
import logging

from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session

from lib import SystemIP, Config
from lib.orm.Ipgoe import IPGoe
from lib.orm.LoginLog import LoginLog

# 连接MySQL数据库，echo=True表示输出日志信息
engine = create_engine(Config.SqlConfig)

cookies = None
queueIdx = 0


def query_ip_baidu(ip):
    url = 'http://gwgp-hrtx4zoqeyk.n.bdcloudapi.com/iplocaltion'
    params = {'ip': ip}

    headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        'X-Bce-Signature': 'AppCode/ff0cd3d4db7141148b77cd453118c945'
    }
    r = requests.request("GET", url, params=params, headers=headers)
    rt = r.json()
    if rt['code'] == 100:
        data = {"ip": ip,
                'country': rt['result']['nation'],
                'province': rt['result']['province'],
                'city': rt['result']['city'],
                'districts': rt['result']['district'],
                'countryCode': rt['result']['en_short']
                }
        return data
    return None


def query_ip(ip):
    url = "https://cz88.net/api/cz88/ip/geo?APPCODE=4abdb9ae-ccf3-34f2-8397-5b830c595f07&ip=" + ip
    try:
        r = requests.get(url,verify=False)
        logging.info("query ip:%s", r.text)
        if r.status_code == 200:
            data = r.json()
            if data['code'] == 200:
                rs = data['data']
                if 'districts' not in rs:
                    rs['districts'] = '未知'
                return rs
    except Exception as e:
        logging.error("query ip error %s", e)
    return None




def push_user_login_log(user_id, ip):
    global queueIdx
    queueIdx += 1
    range_ip = SystemIP.ip_to_left(ip)
    new_user = LoginLog(user_id=user_id, login_ip=ip)
    with Session(engine) as session:
        querry = (select(IPGoe).where(IPGoe.ip == range_ip))
        ip_his = session.scalar(querry)
        if not ip_his:

            # 'country': '中国', 'province': '辽宁', 'city': '大连', 'districts': '沙河口区', 'isp': '中国移动'
            if queueIdx % 20 == 1:
                ipdata = query_ip(ip)
            else:
                ipdata = query_ip_baidu(ip)
            if ipdata and "ip" in ipdata:
                ipData = IPGoe(ip=range_ip, countryCode=ipdata['countryCode'], country=ipdata['country'],
                               districts=ipdata['districts'], city=ipdata['city'], province=ipdata['province'],
                               isp='未知')
                session.add(ipData)
                ip_his = ipData

        if ip_his:
            new_user.country = ip_his.country
            new_user.countryCode = ip_his.countryCode
            new_user.city = ip_his.city
            new_user.districts = ip_his.districts
            new_user.isp = ip_his.isp
            new_user.province = ip_his.province
        # 插入数据

        # 添加到session:
        session.add(new_user)
        session.commit()
        session.close()

# logging.basicConfig(level=logging.INFO,format = '%(asctime)s - %(levelname)s - %(message)s')
# ip = query_ip_baidu('223.102.44.185')
# print(ip)